package com.spice.im;

import java.io.ByteArrayOutputStream;



import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.lang.Thread.UncaughtExceptionHandler;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

//import com.stb.isharemessage.ui.CollapseActivity;
//import com.stb.isharemessage.ui.ContactListWithPop;
//import com.stb.isharemessage.ui.PoupWindowContactList;

import android.content.Context;
import android.content.Intent;
import android.os.Environment;
import android.text.format.Time;
import android.util.Log;

public class CrashHandler implements UncaughtExceptionHandler {
	private UncaughtExceptionHandler mDefaultUEH;
	private SpiceApplication context;
	private static final String LOG_DIR = Environment.getExternalStorageDirectory().getAbsolutePath() + "/beemphoto/log/";
	private static final String LOG_NAME = getCurrentDateString() + ".txt";
	private static String getCurrentDateString() {
		String result = null;
//		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd",Locale.getDefault());
//		Date nowDate = new Date();
//		 result = sdf.format(nowDate);
//		Calendar calendar = Calendar.getInstance();
//		result = calendar.get(Calendar.YEAR)+"-"+(calendar.get(Calendar.MONTH)+1)+"-"+calendar.get(Calendar.DAY_OF_MONTH);
        Time time = new Time("GMT+8");       
        time.setToNow();      
        int year = time.year;      
        int month = time.month;      
        int day = time.monthDay;      
        int minute = time.minute;      
        int hour = time.hour;      
        int sec = time.second;      
        System.out.println("当前时间为：" + year +       
                            "年 " + month +       
                            "月 " + day +       
                            "日 " + hour +       
                            "时 " + minute +       
                            "分 " + sec +       
                            "秒"); 
        result = year+"-"+month+"-"+day;
		return result;
	}

//    private static CrashHandler instance;  //单例引用，这里我们做成单例的，因为我们一个应用程序里面只需要一个UncaughtExceptionHandler实例
   
    public CrashHandler(SpiceApplication context1){
    	mDefaultUEH = Thread.getDefaultUncaughtExceptionHandler();
    	context = context1;
    }
   
//    public synchronized static CrashHandler getInstance(){  //同步方法，以免单例多线程环境下出现异常
//        if (instance == null){
//            instance = new CrashHandler();
//        }
//        return instance;
//    }
   
//    public void init(Context ctx){  //初始化，把当前对象设置成UncaughtExceptionHandler处理器
//    	mDefaultUEH = Thread.getDefaultUncaughtExceptionHandler();
//    }
   
    @Override
    public void uncaughtException(Thread thread, Throwable ex) {  //当有未处理的异常发生时，就会来到这里。。
        Log.e("Sandy", "------------ uncaughtException ------------ " + ex.getMessage());  
        writeErrorLog(ex);
        
//        Intent intent = new Intent(context,CollapseActivity.class);
//        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        intent.putExtra("exctptionmsgstr", ex.getMessage());
        
		
//		Intent intent = new Intent(context, ContactFrameActivity.class);//ContactListPullRefListActivity
//        context.startActivity(intent);
        context.exit();
        
        mDefaultUEH.uncaughtException(thread, ex); // 不加本语句会导致ANR  
//        Log.d("Sandy", "uncaughtException, thread: " + thread
//                + " name: " + thread.getName() + " id: " + thread.getId() + "exception: "
//                + ex);
//             String threadName = thread.getName();
//             if ("sub1".equals(threadName)){
//                   Log.d("Sandy", ""xxx);
//             }else if(){
//                      //这里我们可以根据thread name来进行区别对待，同时，我们还可以把异常信息写入文件，以供后来分析。
//              }
    }

    protected void writeErrorLog(Throwable ex) {
        String info = null;
        ByteArrayOutputStream baos = null;
        PrintStream printStream = null;
        try {
            baos = new ByteArrayOutputStream();
            printStream = new PrintStream(baos);
            ex.printStackTrace(printStream);
            byte[] data = baos.toByteArray();
            info = new String(data);
            data = null;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (printStream != null) {
                    printStream.close();
                }
                if (baos != null) {
                    baos.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        Log.d("example", "崩溃信息\n" + info);
        File dir = new File(LOG_DIR);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        File file = new File(dir, LOG_NAME);
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(file, true);
            fileOutputStream.write(info.getBytes());
            fileOutputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
 
    }
}
